#!/usr/bin/python
from SimpleXMLRPCServer import CGIXMLRPCRequestHandler
import MySQLdb
from config import *
import cgi, cgitb
import os
import random

configure = config()

ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62_encode(num, alphabet=ALPHABET):
    """Encode a number in Base X

    `num`: The number to encode
    `alphabet`: The alphabet to use for encoding
    """
    if (num <= 0):
        return alphabet[0]
    arr = []
    base = len(alphabet)
    while num:
        rem = num % base
        num = num // base
        arr.append(alphabet[rem])
    arr.reverse()
    return ''.join(arr)

def snipURL(email,apikey,url):
    try:
        db = MySQLdb.connect(host=configure.dbHostname,user=configure.dbUsername,passwd=configure.dbPassword,db=configure.dbName)
        sql = """select apikey from link_database_register where email='%s'""" %(email)
        db.query(sql)
        result = db.store_result()
    except MySQLdb.Error, e:
        return "Error %d: %s" % (e.args[0], e.args[1])
    result = result.fetch_row()
    result = result[0][0]
    check = url[:4]
    if(check!="http"):
        url = "http://"+url
    if(result==apikey):
        data = ""
        valRange = ""
        for i in range(5):
            val = random.randint(0,62)
            valRange = valRange + str(val)
            data = data + base62_encode(val)
        ip = cgi.escape(os.environ["REMOTE_ADDR"])
        try:
            db = MySQLdb.connect(host=configure.dbHostname,user=configure.dbUsername,passwd=configure.dbPassword,db=configure.dbName)
            sql = """insert into link_database(hash,link,ipaddress) values(%s,'%s','%s')""" %(valRange,url,ip)
            db.query(sql)
            result = db.store_result()
        except MySQLdb.Error, e:
            return "Error %d: %s" % (e.args[0], e.args[1])
        return configure.url+data
    else:
         return "incorrect apikey not found."

def verifyKey(email,apikey):
    try:
        db = MySQLdb.connect(host=configure.dbHostname,user=configure.dbUsername,passwd=configure.dbPassword,db=configure.dbName)
        sql = """select apikey from link_database_register where email='%s'""" %(email)
        db.query(sql)
        result = db.store_result()
    except MySQLdb.Error, e:
        return "Error %d: %s" % (e.args[0], e.args[1])
    result = result.fetch_row()
    result = result[0][0]
    if(result==apikey):
        return "true"
    else:
        return "false"

server = CGIXMLRPCRequestHandler()
server.register_function(snipURL)
server.register_function(verifyKey)
server.handle_request()